/*
// Definition for a Node.
class Node {
public:
    int val;
    Node* left;
    Node* right;

    Node() {}

    Node(int _val) {
        val = _val;
        left = NULL;
        right = NULL;
    }

    Node(int _val, Node* _left, Node* _right) {
        val = _val;
        left = _left;
        right = _right;
    }
};
*/
class Solution {
public:
    Node* head,*pre;
    Node* treeToDoublyList(Node* root) {
        if(root==nullptr)return nullptr;
        hepler(root);
        head->left=pre;
        pre->right=head;
        return head;        
    }
    void hepler(Node* root){
        if(root==nullptr){
            return ;
        }
        hepler(root->left);
        if(pre==nullptr){
            head=root;
        }else if(pre!=nullptr){
            pre->right=root;
            root->left=pre;
        }
        pre=root;
        hepler(root->right);
    }
};